import React, { PureComponent } from 'react';
import { connect } from 'dva';
import queryString from 'query-string';
import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BatchUpload from '../../components/BatchUpload/Index';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';
import ErrorPage from './ErrorPage';
import Difference from './Difference';

const { confirm } = Modal;
@connect(({ handlediff, loading, socialinsurancehadpay, providentfundhadpay }) => ({
  uploading: loading.effects['publicdata/uploadFile'],
  handlediff,
  socialProgressPercent: socialinsurancehadpay.progressPercent,
  accuProgressPercent: providentfundhadpay.progressPercent,
  socialinsurancehadpay,
}))
class HandleDiff extends PureComponent {
  constructor(props) {
    super(props);
    // const { assType } = queryString.parse(props.location.search);
    this.state = {
      // currentStep: 1,
      // assType: '',
      // resultInfo: {
      //   // 结果数据必传
      //   batchName: '', // 任务名称
      //   taskCount: 0, // 导入数据
      //   successCount: 0, // 成功数据
      //   errorCount: 0, // 失败数据
      //   batchNo: '', // 批次号
      //   errorUrl:
      //     Number(assType) === 1
      //       ? '/osApi/insBillApi/exportExcelErrData'
      //       : '/osApi/accuBillApi/exportExcelErrData', // 下载错误信息地址
      //   errorParams: null, // 下载错误数据参数
      // },
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const batchQuery = queryString.parse(location.search);

    dispatch({
      type: 'handlediff/updateModelData',
      payload: { batchQuery, currentStep: Number(batchQuery.current), assType: batchQuery.assType },
    });
    if (Number(batchQuery.current) === 1) {
      dispatch({
        type: 'handlediff/fetchDiffData',
        payload: {
          pageArg: {
            currentPage: 1,
            pageSize: 10,
          },
        },
      });
    } else {
      dispatch({
        type: 'handlediff/checkTemplate',
        payload: {},
      });
    }
  }

  componentWillUnmount() {
    this.clearModel();
  }

  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handlediff/updateModelData',
      payload: {
        currentStep: 0,
        progressPercent: 0,
        showProgress: false,
        isBackShow: false,
        isError: false,
      },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handlediff/updateModelData',
      payload: {
        currentStep,
      },
    });
    if (!currentStep) {
      dispatch({
        type: 'handlediff/updateModelData',
        payload: {
          progressPercent: 0,
        },
      });
    }
  };

  // 设置页面状态
  setPageState = isError => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handlediff/updateModelData',
      payload: {
        isError,
        progressPercent: 0,
      },
    });
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    const { dispatch } = this.props;
    const {
      handlediff: { batchQuery },
    } = this.props;

    const uploadQuery =
      Number(batchQuery.assType) === 1
        ? {
            insAcco: batchQuery.insAcco,
            payType: batchQuery.payType,
            billId: batchQuery.billId,
          }
        : {
            accuAcco: batchQuery.accuAcco,
            payType: batchQuery.payType,
            billId: batchQuery.billId,
          };
    // 需要携带参数即传：batchQuery，不需要传参可省略
    Object.entries(uploadQuery).forEach(([key, value]) => {
      formData.append(key, value);
    });

    dispatch({
      type: 'handlediff/uploadFileWithProgress',
      payload: formData,
    }).then(res => {
      if (res.success) {
        dispatch({
          type: 'handlediff/updateModelData',
          payload: { showProgress: true },
        });
      }
    });
  };

  handleBackShow = flag => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handlediff/updateModelData',
      payload: {
        isBackShow: !!flag,
      },
    });
  };

  // 显示是否确认回盘
  showBackConfirm = () => {
    const {
      dispatch,
      handlediff: { batchQuery, isBackShow },
    } = this.props;
    if (!isBackShow) {
      return;
    }
    confirm({
      title: '回盘无差异数据',
      okText: '确认回盘',
      cancelText: '取消',
      content: <div style={{ color: '#FAAD14' }}>确认回盘后不可重新回盘和取消回盘？</div>,
      icon: <ExclamationCircleOutlined />,
      onOk: () => {
        dispatch({
          type: 'handlediff/execAffirm',
          payload: {
            billId: batchQuery.billId,
            confirmImport: 1,
          },
        });
      },
      onCancel: () => {
        dispatch({
          type: 'handlediff/execAffirm',
          payload: {
            billId: batchQuery.billId,
            confirmImport: 2,
          },
        });
      },
    });
  };

  render() {
    const {
      handlediff: {
        fileId,
        fileName,
        progressPercent,
        showProgress,
        resultInfo,
        // isBackShow,
        currentStep,
        isError,
      },
      uploading,
    } = this.props;

    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          {isError ? (
            <ErrorPage
              title="上传回盘数据"
              resultInfo={resultInfo}
              setCurrentstep={this.setCurrentstep}
              setPageState={this.setPageState}
            />
          ) : (
            <FileUpload
              title="上传回盘数据"
              currentStep={currentStep}
              setCurrentstep={this.setCurrentstep}
              downloadTempInfo={{
                // 下载模板信息
                params: {
                  fileId,
                  fileName,
                },
                url: '/csApi/fileServer/downloadFile',
              }}
              uploadFile={this.uploadFile}
              uploading={uploading}
              // 展示进度条需要的数据
              progressPercent={progressPercent}
              progressTitle="批量回盘导入"
              progressVisible={showProgress}
              // handleModalVisible={this.handleModalVisible}
            />
          )}
          <Difference title="回盘确认" />
          <Finish
            title="完成"
            resultInfo={resultInfo}
            setCurrentstep={this.setCurrentstep}
            isClose
          />
        </BatchUpload>
        {/* <Modal
          visible={isBackShow}
          title="回盘无差异数据"
          onOk={this.backOk}
          onCancel={this.backCancel}
          okText="确认回盘"
        >
          <div style={{ color: '#FAAD14' }}>确认回盘后不可重新回盘和取消回盘？</div>
        </Modal> */}
        {/* {isBackShow && this.showBackConfirm()} */}
      </PageHeaderWrapper>
    );
  }
}
export default HandleDiff;
